<template>
	<view style="color: #ffffff;">

		<u-toast ref="uToast" />

		<view style="height: 200rpx;">
			<u-row>
				<u-col :span="2">
					<navigator open-type="navigateBack" hover-class="navigator-hover">
						<u-icon name="arrow-left" color="#ffffff" size="50" style="margin: 20rpx 20rpx 20rpx 20rpx;"></u-icon>
					</navigator>
				</u-col>
				<u-col :span="10" style="font-size: 130%;">
					{{title}}
				</u-col>
			</u-row>
		</view>

		<view style="height: 1000rpx;">
			<video v-if="show" ref="myVideo" id="myVideo" style="width: 100%;" :src="src" autoplay :initial-time="initTime"
			 :controls="showProgress" :page-gesture="true" :enable-progress-gesture="showProgress" @timeupdate="forbidDragProgress"
			 @play="playVideo" @ended="videoEnd"></video>
			<u-row style="margin: 0rpx 20rpx;" v-if="!showProgress">
				<u-col :span="1" v-if="isPause" @tap="clickPlayPause">
					<u-icon name="play" custom-prefix="custom-icon" size="35" color="#ffffff"></u-icon>
				</u-col>
				<u-col :span="1" v-else @tap="clickPlayPause">
					<u-icon name="zanting" custom-prefix="custom-icon" size="35" color="#ffffff"></u-icon>
				</u-col>
				<u-col :span="6">
					{{currentTimeOnProgress}} / {{durationTimeOnProgress}}
				</u-col>
				<u-col :span="1" :offset="4" @tap="clickFullScreen">
					<u-icon name="quanping" custom-prefix="custom-icon" size="35" color="#ffffff"></u-icon>
				</u-col>
			</u-row>

			<view style="margin: 20rpx 20rpx;">
				已观看的进度
				<u-line-progress :striped="true" :percent="playVideoPercent" :striped-active="!isPause"></u-line-progress>
			</view>

			<view style="margin: 20rpx 20rpx;">
				小提示：
				<view style="margin-left: 20rpx; margin-top: 20rpx;">
					全屏后滑动左侧可以调节亮度，滑动右侧可以调节音量。
				</view>
			</view>
		</view>

		<!-- <button @tap="testButton">123456</button> -->

	</view>
</template>

<script>
	import {
		getCourseViedoAddressUniapp,
		recordVideoProgressUniapp,
		recordVideoProgressFinishUniapp,
		isCourseEnd
	} from "@/api/modules/course";

	export default {
		data() {
			return {
				url: this.GOBAL.baseURL,
				title: '', // 视频标题
				showProgress: true, // 视频进度条
				videoCurrentTime: 0, // 进度条的时间
				courseChapteID: '', // course_chapter的唯一ID
				courseInfoID: '', // 课程的唯一ID

				initTime: 0, // 视频播放的初始时间
				// initTimeData: 0, 
				show: false, // 显示视频播放组件
				currentTime: 0, // 视频进度条播放的当前时间
				duration: 0, // 当前视频的长度
				playVideoPercent: 0, // 视频播放的总进度
				currentTimeOnProgress: '', // 禁用进度条时显示的当前播放的时间
				durationTimeOnProgress: '', // 禁用进度条时显示的总播放的时间

				isPause: false, // 禁用进度条时，是否暂停
				isEnd: false, // 课程是否结束

				src: '',
				// danmuList: [{
				// 		text: '第 1s 出现的弹幕',
				// 		color: '#ff0000',
				// 		time: 1
				// 	},
				// 	{
				// 		text: '第 3s 出现的弹幕',
				// 		color: '#ff00ff',
				// 		time: 3
				// 	}
				// ],
				// danmuValue: '',

				windowHeight: 0,
			}
		},
		methods: {
			/**
			 * 将秒转换为 分:秒
			 * s int 秒数
			 */
			s_to_hs(s) {
				//计算分钟
				//算法：将秒数除以60，然后下舍入，既得到分钟数
				var h;
				h = Math.floor(s / 60);
				//计算秒
				//算法：取得秒%60的余数，既得到秒数
				s = s % 60;
				//将变量转换为字符串
				h += '';
				s += '';
				//如果只有一位数，前面增加一个0
				h = (h.length == 1) ? '0' + h : h;
				s = (s.length == 1) ? '0' + s : s;
				return h + ':' + s;
			},
			// 禁用进度条时点击暂停/播放按钮
			clickPlayPause() {
				// console.log("Pause")
				if (!this.isPause) {
					this.putLearningObj() // 记录暂停的位置
					this.videoContext.pause();
					this.isPause = true;
				} else {
					this.videoContext.play();
					this.isPause = false;
				}
			},
			// 禁用进度条时点击全屏按钮
			clickFullScreen() {
				// 进入全屏状态
				this.videoContext.requestFullScreen();
			},
			// 视频播放的总进度
			videoPlayPercentMth() {
				// console.log(this.player.cache_.currentTime / this.player.cache_.duration)
				// this.playVideoPercent = this.isDisDragControlBar == false ? 100 + "%" : (this.player.cache_.currentTime / this.player.cache_.duration * 100).toFixed(2) + "%"
				this.playVideoPercent = this.showProgress == true ? 100 : parseInt((this.currentTime / this.duration * 100))
			},
			// 视频播放结束
			videoEnd() {
				this.isPause = true

				this.showProgress = true

				// 发送用户已看完该视频的请求
				let data = {
					courseChapteID: this.courseChapteID + "",
					userEmailString: uni.getStorageSync('loginStorage') // 登陆用户的邮箱
				}
				recordVideoProgressFinishUniapp(data)
					.then(resp => {})
					.catch(resp => {})
			},
			playVideo() {
				this.isPause = false
			},
			putLearningObj() { // 每3秒执行一次
				if (!this.isPause) {
					// putObj(this.learningDuration)
					// console.log('记录播放时间')

					// 记录用户播放的每个视频的进度
					let data = {
						courseChapteID: this.courseChapteID + "", // course_chapter的唯一ID
						videoPlayProgress: this.currentTime + "", // 当前视频时间
						percent: this.currentTime / this.duration + "", // 视频播放的百分比
						courseInfoID: this.courseInfoID, // course_info的唯一ID
						activeIndex: this.courseChapteID, // 当前激活的导航栏
						userEmailString: uni.getStorageSync('loginStorage') // 登陆用户的邮箱
					}
					recordVideoProgressUniapp(data)
						.then(resp => {})
						.catch(resp => {})
				}
			},

			// 播放进度变化时触发
			forbidDragProgress(res) {
				let that = this;
				// console.log(res)
				// let time = res.detail.currentTime;
				// console.log("当前时间" + time)
				// console.log("视频开始的时间" + that.initTimeData)
				// if(time - that.initTimeData > 0)
				// {
				// 	if (parseFloat(time - that.initTimeData).toFixed(3) > 2) {
				// 		// console.log((time - that.videoCurrentTime).toFixed(3))
				// 		let nowtime = parseFloat(that.initTimeData).toFixed(0);
				// 		console.log("!!!!!!!!!!时间回退" + that.initTimeData + '   SEEK ' + nowtime)
				// 		that.initTime = nowtime
				// 		// that.show = false
				// 		// that.$nextTick(function(){
				// 		// 	that.show = true
				// 		// })
				// 		// that.$nextTick(function(){
				// 		// 	that.initTime = parseFloat(time).toFixed(0)
				// 		// })
				// 		this.videoContext.seek(nowtime)
				// 	} else {
				// 		that.initTimeData = parseFloat(time).toFixed(0);

				// 		console.log("更新" + that.initTimeData)
				// 	}
				// that.initTime = parseFloat(time).toFixed(0);
				// }

				that.currentTime = res.detail.currentTime; // 记录视频进度条的时间
				that.duration = res.detail.duration; // 记录视频的总时长
				
				that.currentTimeOnProgress = that.s_to_hs(parseInt(that.currentTime))
				that.durationTimeOnProgress = that.s_to_hs(parseInt(that.duration))
			},
			testButton() {
				// console.log("12345678")
				this.videoContext.seek(20)
				// let that = this;
				// this.show = false;
				// this.$nextTick(() => {
				// 	this.initTime = 0;
				// 	this.show = true;
				// })
			},

			// sendDanmu: function() {
			// 	this.videoContext.sendDanmu({
			// 		text: this.danmuValue,
			// 		color: this.getRandomColor()
			// 	});
			// 	this.danmuValue = '';
			// },
			// videoErrorCallback: function(e) {
			// 	uni.showModal({
			// 		// content: e.target.errMsg,
			// 		content: '视频暂时无法播放，请稍后再试！',
			// 		showCancel: false
			// 	})
			// },
			// getRandomColor: function() {
			// 	const rgb = []
			// 	for (let i = 0; i < 3; ++i) {
			// 		let color = Math.floor(Math.random() * 256).toString(16)
			// 		color = color.length == 1 ? '0' + color : color
			// 		rgb.push(color)
			// 	}
			// 	return '#' + rgb.join('')
			// }
		},
		onLoad(params) {
			let that = this;
			// 发的只是课程视频的id
			// console.log(params.videoID)

			that.courseChapteID = params.videoID;
			that.courseInfoID = params.courseInfoID;

			let data = {
				courseChapterID: params.videoID,
				userEmail: uni.getStorageSync('loginStorage')
			}
			getCourseViedoAddressUniapp(data)
				.then(resp => {
					that.title = params.title;
					that.src = that.url + 'courseVideo/' + resp.data.courseVideo

					// console.log(that.src) // 视频资源地址

					let arr = resp.data.etc.recordCurrentTime.split(".");
					// console.log(parseInt(resp.data.etc.recordCurrentTime))
					// console.log(parseInt(arr[0]))// 视频开始播放的时间
					// console.log(arr)

					// 是否禁用拖动进度条
					if (resp.data.etc.isFinishVideo == "true") {
						that.toast("已定位到上次播放的位置", 1)
						this.showProgress = true;
						this.videoContext.seek(10)
						that.initTime = parseInt(resp.data.etc.recordCurrentTime)
						// that.initTimeData = parseInt(resp.data.etc.recordCurrentTime)
						that.$nextTick(function() {
							that.show = true
						})
					} else {
						that.toast("第一次播放无法快进哦~", 3)
						that.showProgress = false;
						that.initTime = parseInt(resp.data.etc.recordCurrentTime)
						// that.initTimeData = parseInt(resp.data.etc.recordCurrentTime)
						// console.log(that.initTime)
						that.show = true
					}


				})
				.catch(resp => {})

		},
		onReady: function(res) {
			let that = this;

			this.videoContext = uni.createVideoContext('myVideo', that)

			// 进入全屏状态
			// this.videoContext.requestFullScreen();
		},
		destroyed() {
			// console.log("销毁定时器")
			// 如果定时器在运行则关闭
			if (this.timer) {
				clearInterval(this.timer)
			}
			if (this.timer1) {
				clearInterval(this.timer1)
			}
		},
		mounted() {
			let that = this;

			let isEndData = {
				courseId: that.courseInfoID
			}
			isCourseEnd(isEndData)
				.then(resp => {
					if (resp.data.isCourseEnd == "true") {
						that.isEnd = true
						// that.toast("该课程已结束， 播放不再记录", 3)
						// that.toast("该课程已结束， 播放不再记录", 1)
					} else {
						// that.timer = setInterval(that.putLearningObj, 3000) // 每3秒记录一次播放时间
						that.timer = setInterval(function() {
							return that.putLearningObj()
						}, 3000)

						// that.showProgress = false
						that.timer1 = setInterval(function() {
							return that.videoPlayPercentMth()
						}, 500) // 每0.5秒记录一次播放时间，更新总进度
					}
				})
				.catch(resp => {})

			uni.getSystemInfo({
				success: function(res) {
					// console.log(res.model);
					// console.log(res.pixelRatio);
					// console.log(res.windowWidth);
					// console.log(res.windowHeight);
					// console.log(res.language);
					// console.log(res.version);
					// console.log(res.platform);

					// that.windowHeight = res.windowHeight
					// this.windowHeight = res.windowHeight
				}
			});

		},
	}
</script>

<style lang="scss" scoped>
	>>>.wx-video-progress-container {
		visibility: hidden !important;
	}
</style>

<style lang="scss">
	page {
		background-color: #000000;
	}

	>>>.wx-video-progress-container {
		visibility: hidden !important;
	}
</style>
